package threadLocal;

import java.util.Hashtable;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author d11yu
 */
public class ThreadLocalTest {
//    public static final Map<String, Object> DATA = new Hashtable<>();
    public static final ThreadLocal<Object> THREAD_LOCAL = new ThreadLocal<>();
    private static Random random = new Random();
    public static class Task implements Runnable {
        @Override
        public void run() {
            // 在Run方法中，随机生成一个变量（线程要关联的数据），然后以当前线程名为key保存到map中
            Integer i = random.nextInt(1000);
            // 获取当前线程名
            String name = Thread.currentThread().getName();
            System.out.println("线程[" + name + "]生产的随机数是：" + i);
            THREAD_LOCAL.set(i);
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            new OrderService().createOrder();
            Object o = THREAD_LOCAL.get();
            System.out.println("在线程[" + name + "]快结束时关联的数据是：" + o);
        }
    }

    public static void main(String[] args) {
        for (int i = 0; i < 3; i++) {
            new Thread(new Task()).start();
        }
    }
}
